<template>
	<view style="height: 100vh; background: #181818;">
		<!--标题-->
		<bakc text="WLAN" path="pages/newPage/newPage" textMLeft='margin-left: 150rpx;' />
		<view style="height: 60rpx;"></view>

		<!--输入框-->
		<view style="padding:  30rpx;">

			<!--wifi 连接提示-->
			<view class="wifi_tips">
				<view style="font-size: 40rpx; font-weight:900; color: white; ">输入 Wi-Fi 密码</view>
				<view style="height: 10rpx;"></view>
				<view>目前仅支持<text style="color: white;">2.4GHz</text>Wi-Fi网络，</view>
				<view>不支持酒店、机场等需要认证的Wi-Fi</view>
			</view>

			<view style="height: 60rpx;"></view>
			<view class="input" style="background: rgb(53, 53, 53);">
				<u-input style="background: rgb(53, 53, 53);" color='#FFFFFF' border='none' shape='circle'
					placeholder="请输入WIFI名称" v-model="wifiName">
					<template slot="suffix">
						<view class="select_wifi" @click="openPopup">选择wi-fi</view>
					</template>
				</u-input>
			</view>
			<view style="height: 30rpx;"></view>
			<view class="input" style="background: rgb(53, 53, 53);">
				<u-input color='#FFFFFF' style="background: rgb(53, 53, 53);" :password='!isShowWifiPassword'
					border='none' shape='circle' placeholder="请输入WIFI密码" v-model="wifiPassword">
					<template slot="suffix">
						<image @click="isShowWifiPassword = true" v-if="!isShowWifiPassword" src="/static/icon/hide.png"
							style=" width: 23px;height: 22px; opacity: 0.3;" />
						<image @click="isShowWifiPassword = false" v-else src="/static/icon/show.png"
							style=" width: 26px;height: 22px; opacity: 0.3;" />
					</template>
				</u-input>
			</view>


			<!--连接和取消-->
			<view class="button">
				<view class="cancelButton" @click="cancelButton">取消</view>
				<view class="confirmButton" @click="distributionNetwork">连接</view>
			</view>

			<!--弹出层的wifi列表-->
			<u-popup :round="15" :show="showPopup" @close="closePopup" @open="openPopup">
				<view class="popup">
					<view style="height: 30rpx;"></view>
					<view class="title">
						<view style="width: 50px;"></view>
						<view>可用WIFI</view>
						<view @click="refreshWifi" v-if="!isRefreshwifi"
							style="width: 50px;font-size: 30rpx;font-weight: 500;">刷新</view>
						<view v-if="isRefreshwifi" style="width: 50px; margin-top: 25rpx;">
							<u-loading-icon textSize="10"></u-loading-icon>
						</view>
					</view>
					<view style="height: 30rpx;"></view>
					<view style="width: 75%;margin:  0 auto; overflow: auto;height: 800rpx;">
						<view class="item" v-for="item in wifiname" @click="switchWifi(item.SSID)">
							<view> {{ item.SSID  }}</view>
							<view style="width: 85rpx;height: 50rpx;">
								<image @click="empty" :src="signalMethod(item.signalStrength)"
									style="margin-left: 20rpx; width: 50rpx;height: 40rpx;" />
							</view>
						</view>
					</view>
				</view>
			</u-popup>

		</view>
	</view>
</template>

<script>
import amap from '../../static/utils/amap-wx.130.js'
const amapObject = new amap.AMapWX({ key: '650e91753bafb17d33417b8e03bdaa2f' })
	import {
		searchEq,
		bindAd, 
		updateAd
	} from '@/config/api.js';
	export default {
		data() {
			return {
				//蓝牙设备
				bluetoothDevice: {},

				isRefreshwifi: false,
				isRefreshwifiTiem: '',


				//是否配网成功
				network: {
					success: false,
					failure: false,
				},

				timeout: false,
				timeoutMultitimer: '',
				//wifi输入框，绑定的值
				wifiName: '',
				wifiPassword: '',

				//输入WIFI 密码时显示隐藏密码
				isShowWifiPassword: false,

				//弹出层相关变量
				showPopup: false,
				wifiname: [],
				//当前连接的wifi
				presentConnectionWifi: '',
				//wifi信号图片
				wifiSignalImg: [
					"/static/wifi/one_wifi.png",
					"/static/wifi/two_wifi.png",
					"/static/wifi/three_wifi.png",
					"/static/wifi/four_wifi.png",
				],

				//设备状态对象
				equipmentSatus: {
					offline: 1, //离线,
					online: 2, //在线
					newEquipment: 3 //新设备
				},

				wifiTime: '',
				// 初始化map集合
				map: new Map()
			}
		},
		onLoad() {

			//连接蓝牙
			this.createBLEConnection();

			//获取wifi 信息
			this.initWifi();
		},
		methods: {

			//连接蓝牙-------
			createBLEConnection() {
				this.underLoad("连接中....", "蓝牙连接失败", "/pages/newPage/newPage");
				//从vuex中获取到 deviceId
				const deviceId = this.vuex_select_equipment.deviceId;
				let tath = this;
				uni.createBLEConnection({
					deviceId,
					success: res => {
						tath.getBLEDeviceServices(deviceId);
						console.log("连接成功createBLEConnection")
					},
					error: res => {
						console.log("连接失败", res)
					}
				});
			},
			
			//保存用户最近使用的设备
			saveUseTime(item){
				//保存改该设备的一个使用时间
				let evenNumbers = this.vuex_recent_equipment.filter(data=>{
				  let isReturn = data.indexOf(item.mac) > -1;
				  return !isReturn;
				});
				evenNumbers.push(item.mac + ":" + new Date().getTime());
				this.$u.vuex('vuex_recent_equipment',evenNumbers);
			}, 

			//获取蓝牙的所有服务
			getBLEDeviceServices(deviceId) {
				let that = this;
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success: (res) => {
							//获取到蓝牙的服务id
							let serviceId = res.services[0].uuid;
							//将服务id存储到 vuex_select_equipment 对象中
							this.$set(this.vuex_select_equipment, 'serviceId', serviceId);
							that.getBLEDeviceCharacteristics(deviceId, serviceId); //第五步方法名
						},
					});
				}, 1000);
			},

			//建立连接
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				let _that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: (res) => {
						res.characteristics.forEach(characteristic => {
							if (characteristic.properties.write) {
								//获取到蓝牙的写id
								this.$set(this.vuex_select_equipment, 'writeId', characteristic.uuid);
							}
							if (characteristic.properties.notify) {
								//建立蓝牙连接成功之后的，通信凭证
								_that.updateNotify(deviceId, serviceId, characteristic.uuid);
							}
						})
					},
					fail: (res) => {
						console.log("连接失败", res);
					},
				});
			},


			//监听数据
			updateNotify(deviceId, serviceId, characteristicId) {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: characteristicId,
					state: true,
					success: (res) => {
						//显示蓝牙连接成功
						this.timeout = true;
						uni.hideLoading();
						clearTimeout(this.timeoutMultitimer)
						setTimeout(() => {
							this.timeout = false;
						}, 1000)
						//蓝牙连接成功 监听蓝牙数据
						this.listenMessage();
					},
					fail: (res) => {
						console.log("失败1--------", res);
					},
				});
			},


			//加载中....
			underLoad(loadText, timeOutText, route) {
				uni.showLoading({
					title: loadText,
					mask: true
				})
				this.timeoutMethod(timeOutText, route);
			},
			timeoutMethod(text, route) {
				//五秒之后没有反应进行超时提醒
				this.timeoutMultitimer = setTimeout(() => {
					if (!this.timeout) {
						uni.hideLoading();
						uni.showToast({
							title: text,
							icon: 'none'
						});

						//判断是否需要路由跳转
						if (route) {
							//跳转到选择设备页面
							if (route == '/pages/newPage/newPage') {
				
								//调用new_page 页面刷新数据
								this.$bus.$emit('refresh_new_page');
								//断开蓝牙连接
								this.closeBLEConnection();
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/newPage/newPage',
										fail: (e) => {
										}
									});
								}, 880)
							}
						}
					}


				}, 15000)
			},
			//取消蓝牙配网， 断开目前连接的蓝牙去，搜索蓝牙页面
			cancelButton() {
				this.closedBluetoothAndToEquipment();
			},
			closePopup() {
				this.showPopup = false;
			},
			openPopup() {
				this.showPopup = true;
			},
			initWifi() {


				let _this = this;
				uni.startWifi({
					success: (res) => {
						uni.getConnectedWifi({
							success: (resp) => {
								this.wifiName = resp.wifi.SSID

								//判断是苹果用户还是安卓用户
								uni.getSystemInfo({
									success: function(res) {
										// 判断设备平台
										if (res.platform === 'android') {
											//调用wifi 列表
											wx.authorize({
												scope: 'scope.userLocation',
												success(res) {
													// 授权成功，可以进行 WiFi 相关操作
													_this.openWifiMonitor();
												},
												fail(err) {
													// 授权失败，无法进行 WiFi 相关操作
													console.log("用户取消授权---->",
														err);
												}
											});
										}
									}
								});
							},
							fail: (resp) => {
								console.log(resp)
							}
						})
					},
					fail: (res) => {
						console.log(res)
					}
				})
			},

			//刷新wifi
			refreshWifi() {
				this.isRefreshwifi = true;
				this.openWifiMonitorMethod();
				clearTimeout(this.isRefreshwifiTiem);
				this.isRefreshwifiTiem = setTimeout(() => {
					this.isRefreshwifi = false;
					clearInterval(this.wifiTime);
				}, 5000)
			},
			//时候去检测wifi
			openWifiMonitorMethod() {
				clearInterval(this.wifiTime);
				this.wifiTime = setInterval(() => {
					if (this.isRefreshwifi) {
						this.openWifiMonitor();
					}
				}, 1000)
			},

			//开启wifi静态事件
			//开启wifi监听
			openWifiMonitor() {
				var _tath = this;
				wx.getWifiList({ //成功后，就可以获取列表了
					success: function(res) {
						//列表获取成功后，要到事件里提取
						wx.onGetWifiList(function(res) {
							// that.wifiList = res.wifiList
							for (let item of res.wifiList) {
								if (!_tath.map.has(item.SSID) && item.SSID) {
									_tath.map.set(item.SSID, item.SSID);
									_tath.wifiname.push(item);
								}
							}
						})
					},
					fail: (res) => {
						console.log(res)
					}
				});
			},
			
			
			//修改设备信息
			async modifyEquipment(param) {
				 const resp = await updateAd(param);
				 console.log("是否修改成功--->",resp );
			},
			
			//获取到当前配网位置信息
			getCurrentLocation(equipmentId){
				let _this = this;
				amapObject.getRegeo({
				success: (res) => {
				//省市区对象
				var address = res[0].regeocodeData;
				var locationObj = address.addressComponent;
				let param = {};
				if(locationObj.city.length) {
					param = {
						id:equipmentId, 
						province: locationObj.province,
						city: locationObj.city,
						districts: locationObj.district,
					    address: address.formatted_address,
						longitude: res[0].longitude,
					    latitude: res[0].latitude
					}
				}else{
					param = {
						id:equipmentId, 
						province: locationObj.province,
						city: locationObj.province,
						districts: locationObj.district,
					    address: address.formatted_address,
						longitude: res[0].longitude,
					    latitude: res[0].latitude
					}
				}
				 console.log("打印出详细信息",param);
				 //调用修改设备信息接口
				 _this.modifyEquipment(param);
				},
				fail: (err) => {
					console.log(err)
				  }
			  })
			},

			// 显示wifi 信号
			signalMethod(signalStrength) {
				console.log(signalStrength);
				//判断信号
				if (signalStrength > 0 && signalStrength <= 25) {
					return this.wifiSignalImg[0];
				}

				if (signalStrength > 25 && signalStrength <= 50) {
					console.log(this.wifiSignalImg[1]);
					return this.wifiSignalImg[1];
				}

				if (signalStrength > 50 && signalStrength <= 75) {
					return this.wifiSignalImg[2];
				}

				if (signalStrength > 75 && signalStrength <= 100) {
					return this.wifiSignalImg[3];
				}

			},
			//为设备配置网络
			async distributionNetwork() {

				//校验wifi名称和密码是否为空
				if (!this.wifiName.trim()) {
					uni.showToast({
						title: 'WIFI名称不能为空',
						icon: 'none'
					});
					return;
				}

				//判断wifi密码是否为空
				if (!this.wifiPassword.trim()) {
					uni.showToast({
						title: 'WIFI密码不能为空',
						icon: 'none'
					});
					return;
				}

				//配网过程
				this.underLoad("连接中...", "连接超时","/pages/newPage/newPage");

				let param = {
					gbName: this.wifiName,
					gbPassword: this.wifiPassword
				};


				//请求后端让其实对wifi名称和密码进行编码
				uni.request({
					url: 'https://panchizc.com/detection/coding/conversion',
					method: 'POST',
					data: param,
					success: (res) => {
						// console.log(res); 
						//从vuex 中获取到 蓝牙需要的参数
						let equipment = this.vuex_select_equipment;
						this.writeBLECharacteristicValue(
							res.data.data,
							equipment.deviceId,
							equipment.serviceId,
							equipment.writeId);
					},
					fail: (err) => {
						console.error(err); // 请求失败时的处理逻辑
					}
				});



			},
			//切换wifi操作
			switchWifi(SSID) {
				this.wifiName = SSID
				this.closePopup();
			},
			//字符串转换成 16 进制格式

			//配网发送wifi 名称和密码
			//向蓝牙发送数据
			writeBLECharacteristicValue(sendData, deviceId, serviceId, characteristics) {
				console.log("向设备发送的数据---->", sendData);
				let that = this;
				const buffer = new ArrayBuffer(sendData.length)
				const dataView = new DataView(buffer)
				for (let i = 0; i < sendData.length; i++) {
					dataView.setUint8(i, sendData[i]);
				}
				setTimeout(() => {
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: serviceId,
						// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
						characteristicId: characteristics,
						// 这里的value是ArrayBuffer类型
						// value: buffer,
						value: buffer,
						success: (res) => {
							that.returnMessage = res.errMsg;
							console.log("发送成功-----", res);
						},
						fail: (res) => {
							that.returnMessage = res.errMsg;
							console.log("发送失败-----", res);
						},

						complete: (res) => {
							//console.log("发送消息结束----", res)
						}
					});
				}, 1500)


			},
			closedBluetoothAndToEquipment() {
				this.closeBLEConnection();
				
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.$bus.$emit('refresh_new_page');
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/newPage/newPage',
						fail: (e) => {
							console.log(e);
						}
					});
				}, 1000)

			},

			//监听蓝牙发送过来的数据
			listenMessage() {
				let time;
				let _that = this;
				uni.onBLECharacteristicValueChange((res) => {
					let resHex = this.hex2int(res.value);
					
					// 连接蓝牙成功就开始刷新数值
					let value = [resHex[1] * 256 + resHex[2],resHex[3] * 256 + resHex[4]];
					let selectEquipmen = this.vuex_select_equipment;
					this.$set(selectEquipmen, 'mqttValue', value);
					this.$u.vuex('vuex_select_equipment', selectEquipmen);
					//配网成功，关闭蓝牙连接addEquipmentMethod
					if (resHex[0] === 255 && !_that.network.success) {
						_that.network.success = true;
						this.addEquipmentMethod();
						this.closeBLEConnection();
					}
				})
			},

			hex2int(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return parseInt(bit)
					}
				)
				return hexArr
			},

			//关闭蓝牙连接
			closeBLEConnection() {
				uni.closeBLEConnection({
					deviceId: this.vuex_select_equipment.deviceId
				});
			},

			//调用后端添加绑定设备
			async addEquipmentMethod() {
				//获取到当前用户选择的设备对象
				let equipment = this.vuex_select_equipment;
				let param = {
					name: "环境哨兵",
					equipmentMac: equipment.mac,
					appearanceId: equipment.appearance.id,
					sensorId: equipment.sensor.id
				}
				const resp = await bindAd(param);

				//配网成功之后查询该设备
				const device = await searchEq();
				let devices = device.data.items;
				for (let item of devices) {
					//比较找到刚添加的新设备
					if (item.equipmentMac == this.vuex_select_equipment.mac) {
						let deviceObject = {
							id: item.id,
							appearance: item.appearance,
							sensor: item.sensor,
							gas: item.gas,
							mac: item.equipmentMac,
							status: this.equipmentSatus.online,
							timestamp: 0, //时间戳用于计算设备是否离线
							deviceName: item.name,
							mqttValue: ["0", "0"], //给一个默认的值
							timestamp: new Date().getTime()
						}
						
						//调整状态
						let selectEquipmen = this.vuex_select_equipment;
						this.$set(selectEquipmen, 'status', this.equipmentSatus.online);
						this.$set(selectEquipmen, 'deviceName', deviceObject.deviceName);
						this.$u.vuex('vuex_select_equipment',selectEquipmen)
						
						//重新给vuex中的 vuex_select_equipment 赋值
						this.$u.vuex('vuex_new_equipment', deviceObject);
						
						//获取当前位置信息
						this.getCurrentLocation(item.id);

						break;
					}
				}
			

				this.timeout = true;
				uni.hideLoading();
				//显示配网成功
				uni.showToast({
					title: '配网成功',
					icon: 'none'
				});
				
				
				//存储近期使用的key到缓存
				//保存改该设备的一个使用时间	
				this.saveUseTime(this.vuex_select_equipment);
				
				//延迟跳转到首页
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.$bus.$emit('loader_detection');
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/detection/detection',
						fail: (e) => {
							console.log(e);
						}
					});
				}, 1000)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.wifi_tips {
		color: white;
		color: rgb(120, 131, 140);
	}

	.popup {
		height: 509px;
		background: #353535;
		opacity: 1;
		border-radius: 12px 12px 0px 0px;


		.title {
			height: 50px;
			font-size: 18px;
			font-weight: 900;
			color: #FFFFFF;
			opacity: 1;
			text-align: center;
			line-height: 50px;
			display: flex;
			justify-content: space-around;
		}

		.item {
			color: white;
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			font-size: 18px;
			opacity: 0.8;
		}
	}

	.button {
		width: 330px;
		margin: 0 auto;
		text-align: center;
		display: flex;
		justify-content: space-between;
		margin-top: 160rpx;

		.cancelButton {
			color: white;
			width: 137px;
			height: 47px;
			background: linear-gradient(250deg, #353535 0%, #353535 100%);
			opacity: 1;
			border-radius: 18px;
			line-height: 48px;

		}

		.confirmButton {
			width: 137px;
			height: 47px;
			background: #BB9C5F;
			opacity: 1;
			border-radius: 18px;
			line-height: 48px;
			color: white;

		}
	}

	.input {
		height: 62px;
		background: #FFFFFF;
		opacity: 1;
		border-radius: 36rpx;
		margin: 0 auto;
		display: flex;
		border: 1px solid rgba(0, 0, 0, .1);
		padding: 0 39rpx;

		.select_wifi {
			color: white;
			width: 108px;
			height: 58px;
			background: #181818;
			opacity: 1;
			border-radius: 13px;
			text-align: center;
			line-height: 58px;
			font-size: 14px;
			margin: -16px;
		}
	}
</style>